from mcp.server.fastmcp import FastMCP
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("CalculatorServer")

# 创建MCP服务器实例
mcp = FastMCP("Calculator Server")

def validate_numbers(func):
    """参数验证装饰器"""
    def wrapper(a: float, b: float):
        if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
            raise TypeError("参数必须是数字类型")
        return func(a, b)
    return wrapper

@mcp.tool()
@validate_numbers
def add(a: float, b: float) -> float:
    """Add two numbers"""
    return a + b

@mcp.tool()
@validate_numbers
def subtract(a: float, b: float) -> float:
    """Subtract second number from the first"""
    return a - b

@mcp.tool()
@validate_numbers
def multiply(a: float, b: float) -> float:
    """Multiply two numbers"""
    return a * b

@mcp.tool()
@validate_numbers
def divide(a: float, b: float) -> float:
    """Divide first number by the second"""
    if abs(b) < 1e-10:  # 更安全的浮点数零值判断
        raise ValueError("Cannot divide by zero")
    return a / b

if __name__ == "__main__":
    try:
        logger.info("Starting Calculator Server...")
        # 增加超时和错误处理
        mcp.run(transport="stdio", timeout=30, reconnect_attempts=3)
    except Exception as e:
        logger.exception("Server crashed unexpectedly")
        raise